package com.laikan.reader.bookreader.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import com.laikan.library.components.activitys.BasicActivity;
import com.laikan.library.httpvolley.engine.HttpApiRequestEngine;
import com.laikan.library.httpvolley.engine.Requester;
import com.laikan.library.httpvolley.helper.RequestListener;
import com.laikan.library.httpvolley.helper.VolleyErrorHandler;
import com.laikan.library.httpvolley.response.HttpResponse;
import com.laikan.library.managers.ToastMgr;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.R;
import com.laikan.reader.bookfriend.activity.PersonalInfoActivity;
import com.laikan.reader.comment.APIProtocol;
import com.laikan.reader.comment.Constants;
import com.laikan.reader.core.utils.PublicUtil;
import com.socks.library.KLog;
import com.umeng.analytics.MobclickAgent;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

/**
 * 发送评论
 *
 * @author wxl
 */
public class SendCommentActivity extends BasicActivity implements OnClickListener {

    private ScrollView mScrollView;
    private EditText title_edit, content_edit;
    private String title, content, bookid;
    private TextView send_btn;
    private Handler mHandler = new Handler();
    private Drawable drawable_back_tv;
    private ImageView back_tv;
    private RelativeLayout back_layout;
    private TextView tv_comment_count;
    private TextView title_tv;
    private TextView tv_total_count;

    private boolean isFromPersonSign = false; //是否从个性签名进入
    private boolean isFromFocusDetail;
    private String shorteId;

    @Override
    protected void assignViews() {
        setContentView(R.layout.lk_send_comment);
        tv_comment_count = (TextView)findViewById(R.id.tv_comment_count);  //评论字数
        mScrollView = (ScrollView)findViewById(R.id.mscrollview);
        //        mScrollView.post(new Runnable() {  //Android将ScrollView移动到最底部
        //            public void run() {
        //                mScrollView.fullScroll(ScrollView.FOCUS_DOWN);
        //            }
        //        });
        back_layout = (RelativeLayout)findViewById(R.id.back_layout);
        back_tv = (ImageView)findViewById(R.id.back_tv);
        send_btn = (TextView)findViewById(R.id.send_btn);
        title_edit = (EditText)findViewById(R.id.title_edit);
        content_edit = (EditText)findViewById(R.id.content_edit);
        title_tv = (TextView)findViewById(R.id.title_tv);
        tv_total_count = (TextView)findViewById(R.id.tv_total_count);
        content_edit.setOnFocusChangeListener(new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                InputMethodManager imm = ((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE));
                if (hasFocus) {
                    //                    imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

                    //                    mHandler.postDelayed(new Runnable() {
                    //
                    //                        @Override
                    //                        public void run() {
                    //                            // 将ScrollView滚动到底
                    //                            mScrollView.fullScroll(View.FOCUS_DOWN);
                    //
                    //                        }
                    //                    }, 100);
                }else {
                    imm.hideSoftInputFromWindow(content_edit.getWindowToken(), 0);
                }

            }
        });

        title_edit.setOnFocusChangeListener(new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                InputMethodManager imm = ((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE));
                if (hasFocus) {

                }else {
                    imm.hideSoftInputFromWindow(title_edit.getWindowToken(), 0);
                }

            }
        });
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void initData() {
        String action = getIntent().getAction();
        if (action != null) {

            /**
             * 访问不同的接口
             */
            if (action.equals("from_focus_detail")) {       // 从看点
                shorteId = getIntent().getStringExtra("shorteId");
                isFromFocusDetail = true;
                isFromPersonSign = false;
                title_edit.setVisibility(View.GONE);
                title_tv.setText(R.string.mecomment_title_tv);
            }else if (action.equals("from_person_sign")) {    //从个性签名
                String exisContent = getIntent().getStringExtra("exis_content");
                isFromFocusDetail = false;
                isFromPersonSign = true;
                title_edit.setVisibility(View.GONE);
                send_btn.setText(R.string.bookfriend_tv_save);
                title_tv.setText(R.string.person_sign_title_tv);
                content_edit.setText(exisContent);
                content_edit.setHint(R.string.person_sign_count);
                content_edit.setSelection(content_edit.getText().length());
                tv_total_count.setText("50");
            }else {                                          //从书籍详情页
                isFromFocusDetail = false;
                isFromPersonSign = false;
                title_edit.setVisibility(View.VISIBLE);
                title_tv.setText(R.string.sendcomment_title_tv);
            }
        }
        tv_comment_count.setText("0");
        bookid = getIntent().getStringExtra("bookId");
        drawable_back_tv = new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(mContext, R.drawable.lk_back_small), Color.parseColor("#66ccdd")));
        back_tv.setImageDrawable(drawable_back_tv);
    }

    @Override
    protected void setListener() {
        back_layout.setOnClickListener(this);
        send_btn.setOnClickListener(this);
        content_edit.addTextChangedListener(new EditChangedListener());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.send_btn:   //发送评论
                if (isFromFocusDetail) {
                    sendFromFocusDetail();
                }else if (isFromPersonSign) {
                    saveSignIn();
                }else {
                    sendFromBookDetail();
                }
                break;
            case R.id.back_layout:
                title_edit.clearFocus();
                content_edit.clearFocus();
                finish();
                break;
            default:
                break;
        }
    }

    //保存个性签名
    private void saveSignIn() {
        content = content_edit.getText().toString().trim();
//        if (content.length() == 0) {
//            ToastMgr.showShortToast(R.string.person_no_sign);
//            return;
//        }

        showDialog();
        HashMap<String, String> map = new HashMap<>();
        map.put("intro", content);
        map.put("sd", SPUtil.getString("token", ""));
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() {
                KLog.e("---------volley onPreExecute!!!");
            }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                if (httpResponse == null || httpResponse.responseContent == null) {
                    return;
                }
                try {
                    JSONObject obj = new JSONObject(httpResponse.responseContent);
                    KLog.e(httpResponse.responseContent);
                    String result = obj.getString("result");
                    if (Constants.RESULT_OK.equals(result)) {
                        ((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(SendCommentActivity.this.getCurrentFocus().getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
                        Intent intent = new Intent();
                        intent.putExtra("sign",content);
                        setResult(RESULT_OK, intent);
                        finish();
                    }else {
                        ToastMgr.showShortToast(obj.getString("error_msg"));
                    }
                }catch (JSONException e) {
                    ToastMgr.showShortToast(R.string.laikan_data_load_failed);
                    e.printStackTrace();
                }
                dismissDialog();
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                dismissDialog();
                ToastMgr.showShortToast(R.string.laikan_network_anomaly);
            }

            @Override
            public void onFinish() {
            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_person_sign_in);
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);
    }

    private void sendFromFocusDetail() {
        content = content_edit.getText().toString().trim();
        if (content.length() == 0) {
            ToastMgr.showShortToast(R.string.sendcomment_edit_content_hint);
            return;
        }
        if (content.length() < 5) {
            ToastMgr.showShortToast(R.string.sendcomment_edit_content_hint);
            return;
        }

        showDialog();
        HashMap<String, String> map = new HashMap<>();
        map.put("objectId", shorteId);
        map.put("content", content);
        map.put("sd", SPUtil.getString("token", ""));
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() {
                KLog.e("---------volley onPreExecute!!!");
            }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                if (httpResponse == null || httpResponse.responseContent == null) {
                    return;
                }
                try {
                    JSONObject obj = new JSONObject(httpResponse.responseContent);
                    KLog.e(httpResponse.responseContent);
                    String result = obj.getString("result");
                    KLog.e("result:" + result);
                    if (Constants.RESULT_OK.equals(result)) {
                        ((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(SendCommentActivity.this.getCurrentFocus().getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
                        //评论完成后跳转到看点评论列表页面
                        //                        startActivity(new Intent().setClass(mContext, FocusCommentActivity.class).putExtra("shorteId", shorteId));
                        SPUtil.putBoolean("refresh_article_comment", true);
                        finish();
                    }else {
                        ToastMgr.showShortToast(obj.getString("error_msg"));
                    }
                }catch (JSONException e) {
                    ToastMgr.showShortToast(R.string.laikan_data_load_failed);
                    e.printStackTrace();
                }
                dismissDialog();
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                dismissDialog();
                ToastMgr.showShortToast(R.string.laikan_network_anomaly);
            }

            @Override
            public void onFinish() {
            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_book_focus_send_comment);
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);
    }

    private void sendFromBookDetail() {
        title = title_edit.getText().toString().trim();
        content = content_edit.getText().toString().trim();
        if (title.length() == 0) {
            title = "";
        }
        if (content.length() == 0) {
            ToastMgr.showShortToast(R.string.sendcomment_edit_content_hint);
            return;
        }
        if (content.length() < 5) {
            ToastMgr.showShortToast(R.string.sendcomment_edit_content_hint);
            return;
        }

        showDialog();
        HashMap<String, String> map = new HashMap<>();
        map.put("content", content);
        map.put("name", title);
        map.put("sd", SPUtil.getString("token", ""));
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() {
                KLog.e("---------volley onPreExecute!!!");
            }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                if (httpResponse == null || httpResponse.responseContent == null) {
                    return;
                }
                try {
                    JSONObject obj = new JSONObject(httpResponse.responseContent);
                    String result = obj.getString("result");
                    if (Constants.RESULT_OK.equals(result)) {
                        SPUtil.putBoolean("comment_refresh", true);
                        SPUtil.putBoolean("refresh_comment", true);
                        ((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(SendCommentActivity.this.getCurrentFocus().getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
                        finish();
                        //                        if(true){ // 个性签名界面返回
                        //                            setResult(RESULT_OK,new Intent().putExtra("sign",content_edit.getText().toString()));
                        //                        }
                    }else {
                        ToastMgr.showShortToast(obj.getString("error_msg"));
                    }

                }catch (JSONException e) {
                    ToastMgr.showShortToast(R.string.laikan_data_load_failed);
                    e.printStackTrace();
                }
                dismissDialog();

            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                dismissDialog();
                ToastMgr.showShortToast(R.string.laikan_network_anomaly);
                KLog.e("网络不给力，请重试。59");
            }

            @Override
            public void onFinish() {
            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.getRootURL2() + "review/" + bookid + "/add");
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);

    }

    /*
     * (non-Javadoc)
     * @see android.support.v4.app.FragmentActivity#onDestroy()
     */
    @Override
    protected void onDestroy() {

        super.onDestroy();
        if (SendCommentActivity.this.getWindow().getAttributes().softInputMode == WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
            ((InputMethodManager)mContext.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(SendCommentActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
        if (getWindow().getAttributes().softInputMode == WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
            // 隐藏软键盘
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        }
        title_edit.clearFocus();
        content_edit.clearFocus();
    }

    /**
     * 文本输入字数监听
     */
    private class EditChangedListener implements TextWatcher {

        private CharSequence temp;//监听前的文本
        private int editStart;//光标开始位置
        private int editEnd;//光标结束位置
        private final int charMaxNum = 500;
        private final int personCharMaxNum = 50; // 个性签名总数

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            temp = s;
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            tv_comment_count.setText(s.length() + "");

        }

        @Override
        public void afterTextChanged(Editable editable) {

            /** 得到光标开始和结束位置 */
            editStart = content_edit.getSelectionStart();
            editEnd = content_edit.getSelectionEnd();

            if (isFromPersonSign) {
                if (temp.length() > personCharMaxNum) {
                    editable.delete(editStart - 1, editEnd);
                }
                if (temp.length() > personCharMaxNum - 10) {
                    tv_comment_count.setTextColor(Color.RED);
                }else {
                    tv_comment_count.setTextColor(getResources().getColor(R.color.C_999999));
                }
            }else {

                if (temp.length() > charMaxNum) {
                    editable.delete(editStart - 1, editEnd);
                }
                if (temp.length() > charMaxNum - 10) {
                    tv_comment_count.setTextColor(Color.RED);
                }else {
                    tv_comment_count.setTextColor(getResources().getColor(R.color.C_999999));
                }
            }
        }
    }

}
